package com.baizhi.springboot.config;

import com.baizhi.springboot.realm.MyRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfigure {

    /*@Bean
    public HandlerExceptionResolver solver(){
        HandlerExceptionResolver handlerExceptionResolver=new MyExceptionResolver();
        return handlerExceptionResolver;
    }*/

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    @Bean
    public MyRealm getMyRealm() {
        return new MyRealm();
    }
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> map=new HashMap<>();
        //添加shiro内置过滤器，实现权限相关的url拦截
        /**
                  * 常见过滤器：
                  * anon：无需认证（登录）可以访问
                  * authc：必须认证才可以访问
                  * user:如果使用Remember Me的功能，可以直接访问
                  * perms:该资源必须得到资源权限才可以访问
                  * role:该资源必须得到角色权限才可以访问
                  */

        map.put("/admin/login", "anon");
        map.put("/main.jsp", "authc");
        map.put("/deleteBanner", "perms[banner:delete]");
        map.put("/updateBanner", "perms[banner:update]");
        map.put("/insertBanner", "perms[banner:create]");
        map.put("/error.jsp", "anon");
        map.put("/insertRole", "perms[role:create]");
        map.put("/deleteRole", "perms[role:delete]");
        map.put("/updateRole", "perms[role:update]");

        shiroFilterFactoryBean.setUnauthorizedUrl("/error403Page");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;

    }
    @Bean
    public WebSecurityManager getWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

}
